package com.ibm.psbc.cloud;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

public class DubboReferenceBeanFactory<T> implements FactoryBean<T> {
	private Class<T> interfaceClass;
	@Autowired
	ApplicationConfig appConf;
	@Autowired
	RegistryConfig regConf;

	public DubboReferenceBeanFactory(Class<T> interfaceClass) {
		super();
		this.interfaceClass = interfaceClass;
	}

	@Override
	public T getObject() throws Exception {

		ReferenceConfig<T> referenceConfig = new ReferenceConfig<>();

		referenceConfig.setRegistry(regConf);
		referenceConfig.setApplication(appConf);
		int i = (int) (Math.random() * 10) % 2 + 1;
		String group = "DUS" + i;
		System.out.println("group = " + group + " i = " + i);
		referenceConfig.setGroup(group);
		referenceConfig.setInterface(interfaceClass);
		ReferenceConfigCache cache = ReferenceConfigCache.getCache();
		return cache.get(referenceConfig);

	}

	@Override
	public Class<?> getObjectType() {
		return interfaceClass;
	}

}
